package com.example.service;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.example.service.service.MyService;
import com.example.service.service.MyServiceConnection;

public class MainActivity extends AppCompatActivity {

    private Intent intent;
    private ServiceConnection conn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intent = new Intent(this, MyService.class);
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    for (int j = 0; j <10 ; j++) {
                        sleep(1000);
                        Log.d(TAG, "run: "+j);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public void onStartService(View view) {
        startService(intent);
    }

    public void onStopService(View view) {
        stopService(intent);

    }

    public void onBindService(View view) {
        conn = new MyServiceConnection();
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    public void onUnBindService(View view) {
        unbindService(conn);
    }

    private static final String TAG = "MainActivity";
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
        //bindService要unbind,不然就泄露
        if (conn!=null) {
            unbindService(conn);
        }

    }
}